package org.jeecg.modules.yw.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.yw.entity.*;
import org.jeecg.modules.yw.service.EnterPriseService;
import org.jeecg.modules.yw.service.IRequestapproveService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.yw.service.MessagesService;
import org.jeecg.modules.yw.service.RequestEnterPriseService;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DateUtils;
import org.jeecg.modules.yw.utils.UserUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 申请工具审批表
 * @Author: jeecg-boot
 * @Date: 2025-04-15
 * @Version: V1.0
 */
@Api(tags = "申请工具审批表")
@RestController
@RequestMapping("/yw/requestapprove")
@Slf4j
public class RequestapproveController extends JeecgController<Requestapprove, IRequestapproveService> {
    @Autowired
    private IRequestapproveService requestapproveService;
    @Autowired
    private EnterPriseService enterPriseService;
    @Autowired
    private RequestEnterPriseService requestEnterPriseService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private MessagesService messagesService;


    /**
     * 分页列表查询
     *
     * @param
     * @param pageNo
     * @param pageSize
     * @param
     * @return
     */
    //@AutoLog(value = "申请工具审批表-分页列表查询")
    @ApiOperation(value = "申请工具审批表-分页列表查询", notes = "申请工具审批表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<Requestapprove>> queryPageList(@RequestParam(name="id", required = false) String id,
                                                       @RequestParam(name="name", required = false) String name,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<Requestapprove> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(id)) {
            queryWrapper.eq("id", id);
        }
        Page<Requestapprove> page = new Page<Requestapprove>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> roleIds = sysBaseAPI.getRoleIdsByUsername(sysUser.getUsername());
        if (!roleIds.contains(CommonUtils.ADMIN)) {
            String area=sysUser.getArea();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(area)){
                String[] areas=area.split(",");
                StringBuffer st=new StringBuffer();
                for (int i = 0; i < areas.length; i++) {
                    st.append("\""+areas[i]+"\",");
                }
                st=st.deleteCharAt(st.length()-1);
                String sql="(select id from enterprise where city_code in ("+st.toString()+") " +
                        "or (province_code in  ("+st.toString()+") and city_code is null))";
                sql="(select id from request where enterPriseId in("+sql+"))";
                queryWrapper.apply("requestid in"+sql+"");
            }else{
                IPage<Requestapprove> result =new Page<>();
                return Result.ok(result);
            }
        }
        if(StringUtils.isNotBlank(name)){
            String sql="select id from enterprise where name like '%"+name+"%' and delflag='0'";
            sql="(select id from request where enterPriseId in("+sql+"))";
            queryWrapper.apply("requestid in"+sql+"");
        }
        queryWrapper.orderByDesc("createtime");
        IPage<Requestapprove> pageList = requestapproveService.page(page, queryWrapper);
        for (Requestapprove requestapprove1 : pageList.getRecords()) {
            RequestEnterPrise requestEnterPrise = requestEnterPriseService.getById(requestapprove1.getRequestid());
            requestapprove1.setWorkname(enterPriseService.getById(requestEnterPrise.getEnterPriseId()).getName());
            requestapprove1.setRequestEnterPrise(requestEnterPrise);
        }
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param requestapprove
     * @return
     */
    @AutoLog(value = "申请工具审批表-添加")
    @ApiOperation(value = "申请工具审批表-添加", notes = "申请工具审批表-添加")
    //@RequiresPermissions("org.jeecg.modules:requestapprove:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Requestapprove requestapprove) {
        requestapproveService.save(requestapprove);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param requestapprove
     * @return
     */
    @AutoLog(value = "申请工具审批表-编辑")
    @ApiOperation(value = "申请工具审批表-编辑", notes = "申请工具审批表-编辑")
    //@RequiresPermissions("org.jeecg.modules:requestapprove:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Requestapprove requestapprove) {
        requestapproveService.updateById(requestapprove);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "申请工具审批表-通过id删除")
    @ApiOperation(value = "申请工具审批表-通过id删除", notes = "申请工具审批表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:requestapprove:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        requestapproveService.removeById(id);
        return Result.OK("删除成功!");
    }

    @ApiOperation(value = "申请工具审批表-通过id通过", notes = "申请工具审批表-通过id通过")
    @GetMapping(value = "/passById")
    public Result passById(@RequestParam(name = "id", required = true) String id, HttpServletRequest request) {
        Requestapprove lostsomeapprove1 = requestapproveService.getById(id);
        lostsomeapprove1.setApprove("1");
        lostsomeapprove1.setRemark("");
        lostsomeapprove1.setApproveman(UserUtil.getUserId(request, sysBaseAPI));
        lostsomeapprove1.setApprovetime(DateUtils.getCurrentDate());
        requestapproveService.updateById(lostsomeapprove1);
        RequestEnterPrise requeset = requestEnterPriseService.getById(lostsomeapprove1.getRequestid());
        Messages m = new Messages();
        m.setId(CommonUtils.getID());
        m.setMsgType(2);
        m.setNormalMsgType(4);
        m.setCurrentUserId(requeset.getEnterPriseId());
        m.setDelFlag(0);
        String toolName = CommonUtils.getToolName(requeset.getToolType());
        m.setMsgTime(DateUtils.getCurrentTimeDateStr());
        m.setRemark("申请工具:"+toolName+"\n"+"申请数量:"+requeset.getToolNo()+"\n"+ " 申请已通过");
        messagesService.save(m);
        return Result.OK();
    }

    @ApiOperation(value = "申请工具审批表-通过id不通过", notes = "申请工具审批表-通过id不通过")
    @GetMapping(value = "/unpassById")
    public Result unpassById(@RequestParam(name = "id", required = true) String id,
                             @RequestParam(name = "remark",required = false) String remark,
                             HttpServletRequest request) {
        Requestapprove lostsomeapprove1 = requestapproveService.getById(id);
        lostsomeapprove1.setApprove("2");
        lostsomeapprove1.setRemark(remark);
        lostsomeapprove1.setApproveman(UserUtil.getUserId(request, sysBaseAPI));
        lostsomeapprove1.setApprovetime(DateUtils.getCurrentDate());
        requestapproveService.updateById(lostsomeapprove1);
        RequestEnterPrise requeset = requestEnterPriseService.getById(lostsomeapprove1.getRequestid());
        Messages m = new Messages();
        m.setId(CommonUtils.getID());
        m.setMsgType(2);
        m.setNormalMsgType(4);
        m.setCurrentUserId(requeset.getEnterPriseId());
        m.setDelFlag(0);
        m.setMsgTime(DateUtils.getCurrentTimeDateStr());
        String toolName = CommonUtils.getToolName(requeset.getToolType());
        m.setRemark("申请工具:"+toolName+"\n"+"申请数量:"+requeset.getToolNo()+"\n"+ " 申请未通过");
        messagesService.save(m);
        return Result.OK();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "申请工具审批表-批量删除")
    @ApiOperation(value = "申请工具审批表-批量删除", notes = "申请工具审批表-批量删除")
    //@RequiresPermissions("org.jeecg.modules:requestapprove:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.requestapproveService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "申请工具审批表-通过id查询")
    @ApiOperation(value = "申请工具审批表-通过id查询", notes = "申请工具审批表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Requestapprove> queryById(@RequestParam(name = "id", required = true) String id) {
        Requestapprove requestapprove = requestapproveService.getById(id);
        if (requestapprove == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(requestapprove);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param requestapprove
     */
    //@RequiresPermissions("org.jeecg.modules:requestapprove:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Requestapprove requestapprove) {
        return super.exportXls(request, requestapprove, Requestapprove.class, "申请工具审批表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("requestapprove:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Requestapprove.class);
    }

}
